use crate::MetadataError;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::SystemTime;

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BuildInfo {
    pub veryl_version: Option<String>,
    pub generated_files: BTreeMap<PathBuf, SystemTime>,
}

impl BuildInfo {
    pub fn load<T: AsRef<Path>>(path: T) -> Result<Self, MetadataError> {
        let path = path
            .as_ref()
            .canonicalize()
            .map_err(|x| MetadataError::file_io(x, path.as_ref()))?;
        let text = fs::read_to_string(&path).map_err(|x| MetadataError::file_io(x, &path))?;
        Self::from_str(&text)
    }

    pub fn save<T: AsRef<Path>>(&self, path: T) -> Result<(), MetadataError> {
        let mut text = String::new();
        text.push_str("# This file is automatically @generated by Veryl.\n");
        text.push_str("# It is not intended for manual editing.\n");
        text.push_str(&toml::to_string(&self)?);
        fs::write(&path, text.as_bytes()).map_err(|x| MetadataError::file_io(x, path.as_ref()))?;
        Ok(())
    }

    pub fn veryl_version_match(&self) -> bool {
        match &self.veryl_version {
            Some(x) => x == crate::VERYL_VERSION,
            None => false,
        }
    }
}

impl FromStr for BuildInfo {
    type Err = MetadataError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let build_info: BuildInfo = toml::from_str(s)?;
        Ok(build_info)
    }
}
